package com.sntra.beibi.common;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

/**
 * @author moyc
 * @date 2020/5/18.
 */
public class DotUtils {
	/**
	 * (本子铺码) 一英寸里大小 1in=2.54cm=25.40mm
	 */
	public static final float IN_SIZE = 25.40f;
	/**
	 * 码点规格：1.524mm × 1.524mm
	 */
	public static final double DIST_PERUNIT = 1.524d;
	/**
	 * OID3S点码规格
	 */
	public static final double DIST_PERUNIT_3S = 1.27d;

	/**
	 * 计算本子宽高
	 *
	 * @param bitmap 底图的bitmap
	 * @param dpi    打印的dpi
	 * @return
	 * 
	 * 
	 *         public static Double[] calculateBookSize(Bitmap bitmap, int dpi) {
	 *         Double[] pars = new Double[2]; int bmpWidth = bitmap.getWidth(); int
	 *         bmpHeight = bitmap.getHeight(); double bookWidth = ((double) bmpWidth
	 *         / dpi) * IN_SIZE; double bookHeight = ((double) bmpHeight / dpi) *
	 *         IN_SIZE; pars[0] = bookWidth; pars[1] = bookHeight; return pars; }
	 */
	/**
	 * 拼接 x或者y 的dot点
	 *
	 * @param x  dot整数位
	 * @param fx dot小数位
	 * @return
	 */
	public static float joiningTogether(int x, int fx) {
		float point;
		int temporary = x;
		point = fx;
		point /= 100.0;
		point += temporary;
		return point;
	}

	/**
	 * 根据 X点 或者 Y点的dot坐标 转换屏幕坐标
	 *
	 * @param dotPoint         拼接好的dot座标
	 * @param bgSize           绘制view的宽或高
	 * @param pageSize         点码纸的宽或高
	 * @param dotSpecification 码点规格
	 * @return
	 */

	public static float getPoint(float dotPoint, int bgSize, double pageSize, double dotSpecification) {
		dotPoint *= (bgSize);
		float ax = (float) (pageSize / dotSpecification);
		dotPoint /= ax;
		return dotPoint;
	}

	/***
	 * PDF文件转PNG/JPEG图片
	 * 
	 * @param PdfFilePathpdf完整路径
	 * @param imgFilePath图片存放的文件夹
	 * @param dpi越大转换后越清晰，相对转换速度越慢,一般电脑默认96dpi
	 */
	public static String pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
		File file = new File(PdfFilePath);
		String imgUrl = "";
		PDDocument pdDocument = null;
		long now = System.currentTimeMillis();
		try {
			String imgPDFPath = file.getParent();
			int dot = file.getName().lastIndexOf('.');
			// 获取图片文件名
			String imagePDFName = file.getName().substring(0, dot);
			String imgFolderPath = null;
			if (dstImgFolder.equals("")) {
				// 获取图片存放的文件夹路径
				imgFolderPath = imgPDFPath;
			} else {
				imgFolderPath = dstImgFolder;
			} 
			PngDPIProcessor pdpi = new PngDPIProcessor();

			if (createDirectory(imgFolderPath)) {
				pdDocument = PDDocument.load(file);
				PDFRenderer renderer = new PDFRenderer(pdDocument);
				int pages = pdDocument.getNumberOfPages(); // 获取PDF页数
				System.out.println("PDF page number is:" + pages);
				StringBuffer imgFilePath = null;
				for (int i = 0; i < pages; i++) {
					String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
					imgFilePath = new StringBuffer();
					imgFilePath.append(imgFilePathPrefix);
					imgFilePath.append("_");
					imgFilePath.append(String.valueOf(i + 1));
					imgFilePath.append(now + ".png");// PNG
					File dstFile = new File(imgFilePath.toString());
					//System.out.println("文件路径："+dstFile.getPath());。
					renderer.setDefaultDestination(null);
					BufferedImage image = renderer.renderImageWithDPI(i, dpi);
					byte[] ibytes = pdpi.process(image, 300);
				    FileImageOutputStream imageOutput = new FileImageOutputStream(dstFile);
				    imageOutput.write(ibytes, 0, ibytes.length);
				    imageOutput.close();
				}
				System.out.println("PDF文档转PNG图片成功！");
				imgUrl = imgFilePath.toString();
			} else {
				System.out.println("PDF文档转PNG图片失败：" + "创建" + imgFolderPath + "失败");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				pdDocument.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return imgUrl;
	}

	public static boolean createDirectory(String folder) {
		File dir = new File(folder);
		if (dir.exists()) {
			return true;
		} else {
			return dir.mkdirs();
		}
	}

	public static void main(String[] args) {
		String pdfFile = "D:\\docs\\page/gendemo.pdf";
		String destDir = "D:\\docs\\page";
		pdf2Image(pdfFile, destDir, 300);
	}


    public static String decodeLicenseTmatrixKey(String KeyStr)
    {
        char[] array = new char[80];
        char[] array2 = new char[80];
        String text = "";
        int num = 1;
        array = KeyStr.toCharArray();
        int length = KeyStr.length();
        int num2 = 0;
        for (int num3 = 0; num3 < length; num3++)
        {

            int num4 = (byte)(array[num3]);
            if (num3 > 1)
            {
                num2 =  (byte)(array[length + 1 - num3]);
            }
            num4 = num4 * 2 + num * 2 + num2;
            num4 = (num4 * (num3 + num) + num * num3 - 12) % 36;
            if (num4 >= 0 && num4 <= 9)
            {
                array2[num3] = Character.toChars(num4 + 48)[0];
            }
            else
            {
                array2[num3] = Character.toChars(num4 + 55)[0];
            }
            num = num4 * num4 * num3;
            text += array2[num3];
        }
        return text;
    }
	/**
    public static void main(String[] args) {
        try {
            String key = decodeLicenseTmatrixKey("S0,O001,B0101,P000-500,D2025/10/2");
            System.out.println(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    	*/
}
